package com.yanqu.road.server.manger.union;

import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.UnionActivityConditionData;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.entity.task.args.union.UnionActivityBaseArgs;
import com.yanqu.road.entity.task.args.union.UnionRechargeUserArgs;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.bussiness.player.UserActivityBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.helper.UnionHelper;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.logic.rank.UnionActivityRankListModel;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.crossunion.activity.CrossUnionActivityRankDataProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UnionActivityMgr extends TempMgr {

    private static Logger logger = LogManager.getLogger(UnionActivityMgr.class.getName());

    /**
     * 玩家商会活动数据（ActivityId:UserId）
     */
    private static Map<Integer, Map<Long, UserActivityConditionData>> unionUserActivityData;

    /**
     * 商会活动数据
     */
    private static Map<Integer, Map<String, UnionActivityConditionData>> unionActivityData;

    /**
     * 商会活动排行榜
     */
    private static Map<Integer, UnionActivityRankListModel> unionActivityRankListModelMap;

    @Override
    public boolean save() {
        for (Map<String, UnionActivityConditionData> unionActivityConditionDataMap : unionActivityData.values()) {
            for (UnionActivityConditionData data : unionActivityConditionDataMap.values()) {
                if (data.isInsertOption()) {
                    UserActivityBussiness.addUnionActivityConditionData(data);
                } else if (data.isUpdateOption()) {
                    UserActivityBussiness.updateUnionActivityConditionData(data);
                }
            }
        }
        return true;
    }

    @Override
    public boolean reloadData() {
        logger.info("union activity reload start");
        unionUserActivityData = new ConcurrentHashMap<>();
        unionActivityData = new ConcurrentHashMap<>();
        unionActivityRankListModelMap = new ConcurrentHashMap<>();
        for (ActivityInfo activityInfo : NormalActivityMgr.getShowTimeActivityInfoMap().values()) {
            if (ActivityMgr.unionActivityInLoadTime(activityInfo) || ActivityMgr.crossUnionActivityInLoadTime(activityInfo)
                    || ActivityMgr.daFuWengActivityInLoadTime(activityInfo)) {//商会冲榜活动 或者 跨服商会活动
                Map<Long, UserActivityConditionData> userConditionDataMap = UserActivityBussiness.getUnionActivityUserConditionDataMap(activityInfo.getActivityId());
                Map<String, UnionActivityConditionData> unionConditionDataMap = UserActivityBussiness.getUnionActivityConditionDataMap(activityInfo.getActivityId());
                checkUnionActivityConditionData(userConditionDataMap, unionConditionDataMap);
                unionUserActivityData.put(activityInfo.getActivityId(), userConditionDataMap);
                unionActivityData.put(activityInfo.getActivityId(), unionConditionDataMap);
            }
        }
        logger.info("unionActivityIds: {}",unionActivityData.keySet());

        //初始化排行榜数据
        for (Map.Entry<Integer, Map<String, UnionActivityConditionData>> dataEntry : unionActivityData.entrySet()) {
            UnionActivityRankListModel rankListModel = new UnionActivityRankListModel(dataEntry.getKey());
            int rankNum = ActivityHelper.getMaxRank(NormalActivityMgr.getActivityConditionInfoList(dataEntry.getKey()));
            if (rankNum <= 0) {
                rankNum = GameConfig.RANK_DEFAULT_MAX_COUNT;
            }
            rankListModel.setRankNum(rankNum);
            rankListModel.initRankList(dataEntry.getValue());
            unionActivityRankListModelMap.put(dataEntry.getKey(), rankListModel);
            logger.info("put unionActivity : {}",dataEntry.getKey());
        }

        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static UnionActivityRankListModel getUnionActivityRankListModel(int activityId) {
        return unionActivityRankListModelMap.get(activityId);
    }

    public static void removeUnionActivityRank(int activityId, String unionUid){
        UnionActivityRankListModel unionActivityRankListModel = getUnionActivityRankListModel(activityId);
        if(null != unionActivityRankListModel){
            unionActivityRankListModel.removeRank(unionUid);
        }

        //跨服商会争霸活动且在活动期间，商会解散动作会触发
        ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(activityId);
        if(activityInfo.getType() == eActivityType.CrossUnionActivity.getValue() && ActivityMgr.activityInTime(activityInfo)){
            CrossUnionActivityRankDataProto.CrossUnionActivityUserDataMsg.Builder msg = CrossUnionActivityRankDataProto.CrossUnionActivityUserDataMsg.newBuilder();
            msg.setActivityId(activityId);
            msg.setConditionType(0);
            msg.setUserId(0);
            msg.setValue("0");
            msg.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(new UserBaseInfo()));
            msg.setUnionId(unionUid);
            msg.setChangeType(eUnionSyncType.DeleteUnion.getValue());
            Map<Long, Integer> positionMap = CrossUnionMgr.getMemberPositionMap(unionUid);
            for (Map.Entry<Long, Integer> entry : positionMap.entrySet()) {
                Long memberId = entry.getKey();
                Integer pos = entry.getValue();
                CrossUnionActivityRankDataProto.CrossUnionMemberPosDataMsg.Builder builder = CrossUnionActivityRankDataProto.CrossUnionMemberPosDataMsg.newBuilder();
                builder.setPos(pos);
                builder.setUserId(memberId);
                msg.addMember(builder);
            }
            msg.setUnionServerId(CrossUnionMgr.getUnionServerId(unionUid));
            UnionBaseInfo unionBaseInfo = CrossUnionMgr.parseUnionBaseInfo(unionUid);
            if (unionBaseInfo != null) {
                msg.setUnionBaseInfo(UnionBasePb.parseUnionBaseTempMsg(unionBaseInfo));
            }
            if (!CrossUnionMgr.isAllSync()) {
                return;
            }
            YanQuMessage message = YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_UNION_ACTIVITY_USER_VALUE_CHANGE, msg);
            GamePlayerMgr.sendPacket(0, message);
        }else {
            UnionActivityConditionData unionActivityConditionData = getUnionActivityConditionData(activityId, unionUid);
            if (unionActivityConditionData != null) {
                unionActivityConditionData.setMemberPositionMap(new HashMap<>());
                unionActivityConditionData.setValue(BigInteger.ZERO);
                unionActivityConditionData.setMemberUserIdList(new ArrayList<>());
            }
        }
    }

    public static Map<String, UnionActivityConditionData> getUnionActivityConditionDataMap(int activityId){
        return unionActivityData.get(activityId);
    }

    public static UnionActivityConditionData getUnionActivityConditionData(int activityId, String unionUid) {
        Map<String, UnionActivityConditionData> dataMap = getUnionActivityConditionDataMap(activityId);
        if(null != dataMap){
            return dataMap.get(unionUid);
        }
        return null;
    }

    public static List<UserActivityConditionData> getUserActivityConditionDataList(UnionActivityConditionData unionActivityConditionData,
            Map<Long, UserActivityConditionData> userActivityConditionDataMap){
        List<UserActivityConditionData> dataList = new ArrayList<>();
        if(null != unionActivityConditionData && null != userActivityConditionDataMap) {
            for(long userId : unionActivityConditionData.getMemberUserIdList()){
                UserActivityConditionData userActivityConditionData = userActivityConditionDataMap.get(userId);
                if(null != userActivityConditionData){
                    dataList.add(userActivityConditionData);
                }
            }
        }
        return dataList;
    }

    /**
     * 每日0点  重新加载活动数据
     */
    public static void reloadActivityData(Map<Integer, ActivityInfo> activityMap) {
        if (null != unionActivityRankListModelMap) {
            for (ActivityInfo activityInfo : activityMap.values()) {
                if (ActivityMgr.unionActivityInLoadTime(activityInfo)) {
                    if (!unionActivityRankListModelMap.containsKey(activityInfo.getActivityId())) {
                        UnionActivityRankListModel unionActivityRankListModel = new UnionActivityRankListModel(activityInfo.getActivityId());
                        int rankNum = ActivityHelper.getMaxRank(NormalActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId()));
                        if (rankNum <= 0) {
                            rankNum = GameConfig.RANK_DEFAULT_MAX_COUNT;
                        }
                        unionActivityRankListModel.setRankNum(rankNum);
                        unionActivityRankListModelMap.put(activityInfo.getActivityId(), unionActivityRankListModel);
                        unionActivityRankListModel.initRankList();
                    }
                }
            }
        }
    }

    public static int getMyRank(int activityId, String unionUid) {
        UnionActivityRankListModel unionActivityRankListModel = getUnionActivityRankListModel(activityId);
        if(null != unionActivityRankListModel){
            return unionActivityRankListModel.getMyRank(unionUid);
        }
        return -1;
    }

    public static Map<Long, UserActivityConditionData> getUserActivityConditionDataMap(int activityId){
        return unionUserActivityData.get(activityId);
    }

    public static UserActivityConditionData getUserActivityConditionData(int activityId, long userId){
        Map<Long, UserActivityConditionData> dataMap = getUserActivityConditionDataMap(activityId);
        if(null != dataMap){
            return dataMap.get(userId);
        }
        return null;
    }

    public static void setUserActivityConditionData(UserActivityConditionData userActivityConditionData){
        if(null == userActivityConditionData){
            return;
        }
        checkUnionUserConditionData(userActivityConditionData.getActivityId());
        Map<Long, UserActivityConditionData> dataMap = getUserActivityConditionDataMap(userActivityConditionData.getActivityId());
        if(null != dataMap){
            dataMap.put(userActivityConditionData.getUserId(), userActivityConditionData);
        }
    }

    public static void changeUnionInfo(UnionInfo unionInfo) {
        if (null == unionInfo) {
            return;
        }
        if (null != unionActivityData) {
            for (Map.Entry<Integer, Map<String, UnionActivityConditionData>> dataEntry : unionActivityData.entrySet()) {
                ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(dataEntry.getKey());
                //属于活动开始和结束时间
                if (ActivityMgr.activityInTime(activityInfo)) {
                    checkUnionActivityData(dataEntry.getKey(), unionInfo.getUnionUid());
                    UnionActivityConditionData unionActivityConditionData = getUnionActivityConditionData(dataEntry.getKey(), unionInfo.getUnionUid());
                    if (null != unionActivityConditionData) {
                        unionActivityConditionData.setUnionBaseInfo(UnionHelper.parseUnionBaseInfo(unionInfo, UserMgr.getUserInfo(unionInfo.getMasterUserId()), GameServer.getInstance().getServerId()));
                        UnionActivityRankListModel unionActivityRankListModel = getUnionActivityRankListModel(dataEntry.getKey());
                        if(null != unionActivityRankListModel) {
                            unionActivityRankListModel.rankChange(unionActivityConditionData);
                        }
                    }
                }
            }
        }
    }

    /**
     * 玩家的活动数据更新所在商会的活动数据
     * @param unionUid
     * @param unionExp
     */
    public static void addUnionActivityValue(int activityId, String unionUid, long unionExp) {
        UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        if (null != unionInfo) {
            if(unionExp == 0){
                return;
            }
            ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(activityId);
            //属于活动开始和结束时间
            if (ActivityMgr.activityInTime(activityInfo)) {
                checkUnionActivityData(activityId, unionUid);
                UnionActivityConditionData unionActivityConditionData;
                synchronized (unionActivityData) {
                    unionActivityConditionData = changeUnionActivityConditionData(activityId, unionUid, unionInfo, unionActivityData);
                    calcUnionActivityConditionValue(unionActivityConditionData, getUserActivityConditionDataMap(activityId));
                }
                UnionActivityRankListModel unionActivityRankListModel = getUnionActivityRankListModel(activityId);
                if (null != unionActivityRankListModel) {
                    unionActivityRankListModel.rankChange(unionActivityConditionData);
                }
                //以上逻辑不改，将跨服商会数据变更进行上传，
                if (activityInfo.getType() == eActivityType.CrossUnionActivity.getValue()) {
                    //跨服商会争霸,商会存在情况会触发
                  //  CrossDataMgr.unionActivityRandChange(activityId, unionActivityConditionData, false);
                }
            }
        }
    }

    /**
     * 玩家的活动数据更新所在商会的活动数据
     * @param activityId
     * @param unionUid
     * @param userId
     * @param userActivityConditionData
     * @param notifyType
     */
    public static void changeUnionActivityValue(int activityId, String unionUid, long userId, UserActivityConditionData userActivityConditionData, int notifyType) {
        UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        if (null != unionInfo) {
            ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(activityId);
            //属于活动开始和结束时间
            if (ActivityMgr.activityInTime(activityInfo)) {
                if (activityInfo.getType() == eActivityType.UnionRankActivity.getValue()) {
                    checkUnionActivityData(activityId, unionUid);
                    UnionActivityConditionData unionActivityConditionData;
                    synchronized (unionActivityData) {
                        unionActivityConditionData = changeUnionActivityConditionData(activityId, unionUid, unionInfo, unionActivityData);
                        if(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL == notifyType || UnionRiseRankArgs.NOTIFY_TYPE_JOIN == notifyType){
                            if(null != userActivityConditionData) {
                                unionActivityConditionData.addMemberUserId(userActivityConditionData.getUserId());
                                setUserActivityConditionData(userActivityConditionData);
                                UnionActivityMgr.changeUnionMemberPositionData(unionUid,userId,unionActivityConditionData);
                            }
                        }else if(UnionRiseRankArgs.NOTIFY_TYPE_REMOVE == notifyType || UnionRiseRankArgs.NOTIFY_TYPE_DELETE == notifyType){
                            UnionActivityMgr.changeUnionMemberPositionData(unionUid,userId,unionActivityConditionData);
                        }else if(UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE == notifyType){
                            UnionActivityMgr.changeUnionMemberPositionData(unionUid,userId,unionActivityConditionData);
                        }
                        calcUnionActivityConditionValue(unionActivityConditionData, getUserActivityConditionDataMap(activityId));
                    }
                    UnionActivityRankListModel unionActivityRankListModel = getUnionActivityRankListModel(activityId);
                    if(null != unionActivityRankListModel) {
                        if(unionActivityConditionData.getMemberUserCount() > 0) {
                            unionActivityRankListModel.rankChange(unionActivityConditionData);
                        }else {
                            unionActivityRankListModel.removeRank(unionUid);
                        }
                    }
                    return;
                    //以上逻辑不改，将跨服商会数据变更进行上传，
                  /*  if(activityInfo.getType() == eActivityType.CrossUnionActivity.getValue() && UnionRiseRankArgs.NOTIFY_TYPE_DELETE != notifyType){
                        //跨服商会争霸,商会存在情况会触发
                        //   CrossDataMgr.unionActivityRandChange(activityId,unionActivityConditionData, false);
                    } else if (activityInfo.getType() == eActivityType.DaFuWeng.getValue() && UnionRiseRankArgs.NOTIFY_TYPE_DELETE != notifyType) {
                        //   CrossDataMgr.unionActivityRandChange(activityId, unionActivityConditionData, false);
                    }*/
                }

                CrossUnionActivityRankDataProto.CrossUnionActivityUserDataMsg.Builder msg = CrossUnionActivityRankDataProto.CrossUnionActivityUserDataMsg.newBuilder();
                if (userActivityConditionData == null) {
                    userId = 0;
                    msg.setValue("0");
                }else {
                    msg.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(userId, GameServer.getInstance().getServerId())));
                    msg.setValue(userActivityConditionData.getValue().toString());
                }
                msg.setActivityId(activityId);
                if (activityInfo.getType() == eActivityType.Tomb.getValue()) {
                    msg.setConditionType(eGamePlayerEventType.TombUnionRank.getValue());
                } else {
                    msg.setConditionType(0);
                }
                msg.setUserId(userId);
                msg.setUnionId(unionUid);
                msg.setChangeType(notifyType);
                Map<Long, Integer> positionMap = CrossUnionMgr.getMemberPositionMap(unionUid);
                for (Map.Entry<Long, Integer> entry : positionMap.entrySet()) {
                    Long memberId = entry.getKey();
                    Integer pos = entry.getValue();
                    CrossUnionActivityRankDataProto.CrossUnionMemberPosDataMsg.Builder builder = CrossUnionActivityRankDataProto.CrossUnionMemberPosDataMsg.newBuilder();
                    builder.setPos(pos);
                    builder.setUserId(memberId);
                    msg.addMember(builder);
                }
                msg.setUnionServerId(CrossUnionMgr.getUnionServerId(unionUid));
                UnionBaseInfo unionBaseInfo = CrossUnionMgr.parseUnionBaseInfo(unionUid);
                if (unionBaseInfo != null) {
                    msg.setUnionBaseInfo(UnionBasePb.parseUnionBaseTempMsg(unionBaseInfo));
                }
                if (!CrossUnionMgr.isAllSync()) {
                    return;
                }
                YanQuMessage message = YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_UNION_ACTIVITY_USER_VALUE_CHANGE, msg);
                GamePlayerMgr.sendPacket(0, message);
            }
        }
    }

    //非沖榜活動的保存数据
    public static void saveUnionActivityValue(int activityId,UserActivityConditionData userActivityConditionData, UnionActivityBaseArgs args) {
        String unionUid = args.getUnionUid();
        UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        if (null != unionInfo) {
            ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(activityId);
            //属于活动开始和结束时间
            if (ActivityMgr.activityInTime(activityInfo)) {
               /* checkUnionActivityData(activityId, unionUid);
                UnionActivityConditionData unionActivityConditionData;
                synchronized (unionActivityData) {
                    unionActivityConditionData = changeUnionActivityConditionData(activityId, unionUid, unionInfo, unionActivityData);
                    if(UnionActivityBaseArgs.VALUE_IN == args.getType()){
                        if(null != userActivityConditionData) {
                            unionActivityConditionData.addMemberUserId(userActivityConditionData.getUserId());
                            unionActivityConditionData.setInfo(args.addInfo(unionActivityConditionData.getInfo()));
                            userActivityConditionData.setValue(args.getFinalValue(unionActivityConditionData.getInfo()));
                        }
                    }else if(UnionActivityBaseArgs.VALUE_OUT == args.getType()){
                        unionActivityConditionData.setInfo(args.removeInfo(unionActivityConditionData.getInfo()));
                    }
                }*/
                //发到跨服吧
                if (activityInfo.getType() == 11 && args instanceof UnionRechargeUserArgs) {
                    UnionRechargeUserArgs rechargeUserArgs = (UnionRechargeUserArgs) args;
                    CrossUnionActivityRankDataProto.CrossUnionRechargeChangeMsg.Builder req = CrossUnionActivityRankDataProto.CrossUnionRechargeChangeMsg.newBuilder();
                    req.setActivityId(activityId);
                    CrossUnionActivityRankDataProto.UnionRechargeArgMsg.Builder argMsg = CrossUnionActivityRankDataProto.UnionRechargeArgMsg.newBuilder();
                    argMsg.setAddValue(rechargeUserArgs.getAddValue());
                    argMsg.setGetReward(rechargeUserArgs.isGetReward());
                    argMsg.setUserId(userActivityConditionData.getUserId());
                    argMsg.setUnionId(unionUid);
                    argMsg.setType(rechargeUserArgs.getType());
                    argMsg.setConditionId(rechargeUserArgs.getConditionId());
                    req.setArg(argMsg);
                    req.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(userActivityConditionData.getUserId(), GameServer.getInstance().getServerId())));
                    //获取一下商会成员区服集合
                    List<Long> serverList = new ArrayList<>();
                    Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
                    if(null != memberMap){
                        for(CrossUnionMember member : memberMap.values()){
                            if(!serverList.contains(member.getServerId())){
                                serverList.add(member.getServerId());
                            }
                        }
                    }
                    req.addAllServerList(serverList);
                    YanQuMessage message = YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_UNION_RECHARGE_ACTIVITY_CHANGE, req);
                    GamePlayerMgr.sendPacket(0,message);
                }
            }
        }
    }

    //特殊的活动要通知特殊的东西(客户端红点)，商会充值活动通知领取奖励的人数
    public static void notifyAllMemberSpecial(String unionUid,UserActivityConditionData userActivityConditionData,UnionActivityBaseArgs args){
        Map<Long, CrossUnionMember> unionMemberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
        for(UnionMember member : unionMemberMap.values()){
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(member.getUserId());
            if(player != null){
                //商会充值活动通知领取奖励的人数
                if(userActivityConditionData.getType() == eGamePlayerEventType.UnionRechargeUser.getValue()){
                    if(args instanceof UnionRechargeUserArgs){
                        if(((UnionRechargeUserArgs)args).isGetReward()){
                            player.getModule(ActivityModule.class).syncUnionRecharge(userActivityConditionData.getActivityId());
                        }
                    }
                }
            }
        }
    }


    //通知所有有这个活动的玩家
    public static void notifyAllMemberActivity(String unionUid,long userId,int notifyEvent){
        Map<Long, CrossUnionMember> unionMemberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
        for(UnionMember member : unionMemberMap.values()){
            if(member.getUserId() != userId){
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(member.getUserId());
                if(player != null){
                    UnionRechargeUserArgs unionRechargeUserArgs = new UnionRechargeUserArgs(UnionRechargeUserArgs.VALUE_IN,0,unionUid,member.getUserId());
                    player.notifyListener(notifyEvent, unionRechargeUserArgs);
                }
            }
        }
    }

    //根据活动类型来判断要通知哪个
    private static void notifyByActivity(GamePlayer player,ActivityInfo activityInfo,BigInteger value){
        if(activityInfo.getType() == eActivityType.UnionActivity.getValue()){
            switch (activityInfo.getChildType()){
                case 1:
                    UnionRechargeUserArgs args = new UnionRechargeUserArgs(0,0,"",0);
                    args.setSetValue(value);
                    player.notifyListener(eGamePlayerEventType.UnionRechargeUser.getValue(),args);
                    break;
            }
        }
    }


    public static UnionActivityConditionData getUnionActivityConditionData(int activityId, long userId){
        Map<String, UnionActivityConditionData> dataMap = getUnionActivityConditionDataMap(activityId);
        if(null != dataMap){
            for(UnionActivityConditionData unionActivityConditionData : dataMap.values()){
                if(unionActivityConditionData.hasMemberUserId(userId)){
                    return unionActivityConditionData;
                }
            }
        }
        return null;
    }

    public static UnionActivityConditionData getUnionActivityConditionDataByUnionUid(int activityId, String unionUid){
        Map<String, UnionActivityConditionData> dataMap = getUnionActivityConditionDataMap(activityId);
        if(null != dataMap){
            for(String acUnionUid : dataMap.keySet()){
                if(acUnionUid.equals(unionUid)){
                    return dataMap.get(acUnionUid);
                }
            }
        }
        return null;
    }

    public static void calcUnionActivityConditionValue(UnionActivityConditionData unionActivityConditionData, Map<Long, UserActivityConditionData> userActivityConditionDataMap){
        BigInteger value = BigInteger.ZERO;
        if(null != unionActivityConditionData && null != userActivityConditionDataMap) {
            BigInteger oldValue = unionActivityConditionData.getValue();
            for (long userId : unionActivityConditionData.getMemberUserIdList()) {
                UserActivityConditionData userActivityConditionData = userActivityConditionDataMap.get(userId);
                if (userActivityConditionData != null) {
                    value = value.add(userActivityConditionData.getValue());
                }
            }
            if(0 != oldValue.compareTo(value)){
                unionActivityConditionData.setLastUpdateTime(System.currentTimeMillis() / 1000);
            }
            BigInteger tradeAdd = BigInteger.ZERO;
            try{
                ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(unionActivityConditionData.getActivityId());
                if(null != activityInfo && ((activityInfo.getType() == eActivityType.UnionRankActivity.getValue() && activityInfo.getChildType() ==2) ||
                        (activityInfo.getType() == eActivityType.CrossUnionActivity.getValue() && activityInfo.getChildType() == 3))) {
                    UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionActivityConditionData.getUnionUid());
                    if (unionActivityConditionData.getActivityId() == unionInfo.getRankActivityId()) {
                        tradeAdd = BigInteger.valueOf(unionInfo.getRankAddExp());
                    }
                }
            }catch (Exception e){
                logger.error(" union rank add exp error.");
            }
            unionActivityConditionData.setValue(value.add(tradeAdd));
        }
    }

    /**
     * 获取用户对应职位的奖励
     * @param unionActivityConditionData
     * @param activityConditionInfo
     * @param userId
     * @return
     */
    public static  String getUnionMemberPositionDataReward(UnionActivityConditionData unionActivityConditionData, ActivityConditionInfo activityConditionInfo, long userId){
        try {
            if (activityConditionInfo == null) {
                return "";
            }
            if (unionActivityConditionData == null) {
                return activityConditionInfo.getRewardStr();
            }

            if (unionActivityConditionData.getMemberPositionMap().containsKey(userId)) {
                int position = unionActivityConditionData.getMemberPositionMap().get(userId);
                //没有配置获取普通用户奖励
                if (position == eUnionPosition.DeputyMaster.getValue()) {
                    return StringUtils.isNullOrEmpty(activityConditionInfo.getDeputyMasterRewardStr()) ? activityConditionInfo.getRewardStr() : activityConditionInfo.getDeputyMasterRewardStr();
                } else if (position == eUnionPosition.Elite.getValue()) {
                    return StringUtils.isNullOrEmpty(activityConditionInfo.getEliteRewardStr()) ? activityConditionInfo.getRewardStr() : activityConditionInfo.getEliteRewardStr();
                }
            }
            return activityConditionInfo.getRewardStr();
        } catch (Exception e) {
            logger.error("getUnionMemberPositionDataReward", e);
            return activityConditionInfo.getRewardStr();
        }
    }


    public static  String getUnionMemberPositionDataReward(int position, ActivityConditionInfo activityConditionInfo, long userId){
        try {
            if (activityConditionInfo == null) {
                return "";
            }
            //没有配置获取普通用户奖励
            if (position == eUnionPosition.Master.getValue()) {
                return StringUtils.isNullOrEmpty(activityConditionInfo.getMasterRewardStr()) ? activityConditionInfo.getRewardStr() : activityConditionInfo.getMasterRewardStr();
            }else if (position == eUnionPosition.DeputyMaster.getValue()) {
                return StringUtils.isNullOrEmpty(activityConditionInfo.getDeputyMasterRewardStr()) ? activityConditionInfo.getRewardStr() : activityConditionInfo.getDeputyMasterRewardStr();
            } else if (position == eUnionPosition.Elite.getValue()) {
                return StringUtils.isNullOrEmpty(activityConditionInfo.getEliteRewardStr()) ? activityConditionInfo.getRewardStr() : activityConditionInfo.getEliteRewardStr();
            }
            return activityConditionInfo.getRewardStr();
        } catch (Exception e) {
            logger.error("getUnionMemberPositionDataReward", e);
            return activityConditionInfo.getRewardStr();
        }
    }

    /**
     * 改变用户活动期间职位
     * @param unionUid
     * @param userId
     * @param unionActivityConditionData
     */
    public static  void changeUnionMemberPositionData(String unionUid, long userId, UnionActivityConditionData unionActivityConditionData){
        try {
            Map<Long, CrossUnionMember> unionMemberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
            if (unionMemberMap == null) {
                unionActivityConditionData.setMemberUserIdList(new ArrayList<>());
                unionActivityConditionData.setMemberPositionMap(new HashMap<>());
            }else {
                unionActivityConditionData.setMemberUserIdList(new ArrayList<>(unionMemberMap.keySet()));
                for (CrossUnionMember member : new ArrayList<>(unionMemberMap.values())) {
                    unionActivityConditionData.changeMemberPosition(member.getUserId(), member.getPosition());
                }
            }
        } catch (Exception e) {
            logger.error("changeUnionMemberPositionData", e);
        }
    }

    /**
     * 刷新商会condition的职位数据
     */
    public static void refreshUnionMemberPositionData(String unionUid, UnionActivityConditionData unionActivityConditionData) {
        CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        if (unionInfo == null) return;
        Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
        if (memberMap == null) return;
        // 设置会长
        unionActivityConditionData.setUnionBaseInfo(CrossUnionMgr.parseUnionBaseInfo(unionInfo));
        // 设置副会长、精英
        Map<Long, Integer> positionMap = new ConcurrentHashMap<>();
        for (UnionMember member : memberMap.values()) {
            if (member.getPosition() == eUnionPosition.DeputyMaster.getValue() || member.getPosition() == eUnionPosition.Elite.getValue()) {
                positionMap.put(member.getUserId(), member.getPosition());
            }
        }
        unionActivityConditionData.setMemberPositionMap(positionMap);
    }

    public static UnionActivityConditionData changeUnionActivityConditionData(int activityId, String unionUid, UnionInfo unionInfo,
            Map<Integer, Map<String, UnionActivityConditionData>> unionActivityDataMap) {
        UnionActivityConditionData unionActivityConditionData = unionActivityDataMap.get(activityId).get(unionUid);
        if (unionActivityConditionData == null && unionInfo != null) {
            unionActivityConditionData = new UnionActivityConditionData();
            unionActivityConditionData.setActivityId(activityId);
            unionActivityConditionData.setGetReward(false);
            unionActivityConditionData.setUnionUid(unionInfo.getUnionUid());
            unionActivityConditionData.setInfo("{}");
            unionActivityConditionData.setLastUpdateTime(System.currentTimeMillis() / 1000);
            unionActivityConditionData.setInsertOption();
            unionActivityDataMap.get(activityId).put(unionUid, unionActivityConditionData);
        }
        if (unionInfo != null) {
            unionActivityConditionData.setUnionBaseInfo(CrossUnionMgr.parseUnionBaseInfo(unionUid));
        }
        return unionActivityConditionData;
    }

    public static void checkUnionActivityConditionData(Map<Long, UserActivityConditionData> userActivityConditionDataMap,
                                                       Map<String, UnionActivityConditionData> unionActivityConditionDataMap) {
        for(UnionActivityConditionData unionConditionData : unionActivityConditionDataMap.values()){
            BigInteger value = BigInteger.ZERO;
            List<Long> deleteUserIdList = new ArrayList<>();
            for(long userId : unionConditionData.getMemberUserIdList()){
                UserActivityConditionData userActivityConditionData = userActivityConditionDataMap.get(userId);
                if(null != userActivityConditionData){
                    userActivityConditionData.setUnionUid(unionConditionData.getUnionUid());
                    value = value.add(userActivityConditionData.getValue());
                }else {
                    deleteUserIdList.add(userId);
                }
            }
            unionConditionData.setValue(value);
            for(long userId : deleteUserIdList){
                unionConditionData.removeMemberUserId(userId);
            }
        }
    }

    private static void checkUnionUserConditionData(int activityId){
        if(!unionUserActivityData.containsKey(activityId)){
            synchronized (unionUserActivityData){
                if(!unionUserActivityData.containsKey(activityId)){
                    unionUserActivityData.put(activityId, new ConcurrentHashMap<>());
                }
            }
        }
    }

    private static void checkUnionActivityData(int activityId, String unionUid) {
        if (!StringUtils.isNullOrEmpty(unionUid)) {
            if (!unionActivityData.containsKey(activityId)) {
                synchronized (unionActivityData) {
                    if (!unionActivityData.containsKey(activityId)) {
                        unionActivityData.put(activityId, new ConcurrentHashMap<>());
                    }
                }
            }
        }
    }

    public static int canChangeUnion() {
        Map<Integer, ActivityInfo> showTimeActivityInfoMap = NormalActivityMgr.getShowTimeActivityInfoMap();
        for (ActivityInfo info : showTimeActivityInfoMap.values()) {

            eUnionActivityGroupType type = eUnionActivityGroupType.getType(info.getType());
            if (type == null){
                continue;
            }
            //不是所名单的处理
            if (!type.isLockMember()){
                //这个活动类型需要分组 并且 活动还没结束
                if (UnionActivityGroupHelper.needGroup(info) && ActivityMgr.activityBeforeEndTime(info)){
                    boolean haveGroup = GameUnionActivityGroupMgr.haveGroup(info.getActivityId());
                    if (haveGroup){
                        return GameErrorCode.E_UNION_ACTIVITY_GROUP_CAN_NOT_CHANGE_UNION;
                    }
                }
            }

        }
        return 0;
    }
}
